/**
 * @Author YuanYuan
 * @Date 2022/7/30
 * @Time 9:12
 */
public class Sort {
    public void heapSort(int[] arr) {
        if(0 == arr.length) {
            return;
        }
        creatBigHeap(arr);
        int end = arr.length-1;
        while(end>=0) {
            swap(arr,0,end);
            shiftDown(arr,0,end);
            end--;
        }
    }
    private void creatBigHeap(int[] arr) {
        for (int parent = (arr.length-1-1)/2; parent >=0 ; parent--) {
            shiftDown(arr,parent,arr.length);
        }
    }
    private void shiftDown(int[] arr,int parent,int len) {
        int child = parent*2 + 1;
        while(child<len) {
            if(child+1<len&&arr[child+1]>arr[child]) {
                child++;
            }
            if(arr[child] > arr[parent]) {
                swap(arr,child,parent);
                parent = child;
                child = parent*2 + 1;
            }else {
                break;
            }
        }
    }
    private void swap(int[] arr,int left,int right) {
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
    }
    /**
     * 时间复杂度:n*logn
     * 稳定排序
     * @return void
    */
    public void mergerSort(int[] arr) {
        mergerSortFun(arr,0,arr.length-1);
    }
    private void mergerSortFun(int[] arr,int left,int right) {
        if(left>=right) {
            return;
        }
        int mid = (left+right)/2;
        mergerSortFun(arr,left,mid);
        mergerSortFun(arr,mid+1,right);
        //进行归并
        merger(arr,left,right,mid);
    }
    private void merger(int[] arr,int left,int right,int mid) {
        int s1 = left;
        int s2 = mid+1;
        int e1 = mid;
        int e2 = right;
        int[] tmpArr = new int[right-left+1];
        //记录temArr的下标
        int k = 0;
        while(s1<=e1&&s2<=e2) {
            if(arr[s1]<arr[s2]) {
                tmpArr[k++] = arr[s1++];
            }else {
                tmpArr[k++] = arr[s2++];
            }
        }
        //有一个没走完
        while(s1<=e1)
        {
            tmpArr[k++] = arr[s1++];
        }
        while(s2<=e2)
        {
            tmpArr[k++] = arr[s2++];
        }

        //注意!不可以直接i = left 因为left可能大于k!!!
        for (int i = 0; i < k; i++) {
            arr[i+left] = tmpArr[i];
        }
    }
    public void shellSort(int[] arr) {
        int[] ret = {3,4,2,1};
        for (int i = 0; i < ret.length; i++) {
            shellSortfun(arr,ret[i]);
        }

    }
    private void shellSortfun(int[] arr,int src) {
        int j = 0;
        for (int i = 0; i < arr.length; i++) {
            int ret = arr[i];
            for (j = i-src; j >=0 ; j-=src) {
                if(arr[j]>ret) {
                    arr[j+src] = arr[j];
                }else {
                    break;
                }
            }
            arr[j+src] = ret;
        }
    }
}
